package poxer

import groovy.util.Eval;
import com.sun.net.httpserver.*;

/**
 *
 * @author Joel
 */
class PoxerServ {

    def run = { port, fname ->

        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
          // parse file
        def contexts = [
            [
                when: '/movies?y=1996',
                then: '''
                <movies year="1996">
                  <movie title="Silence of the Lambs">
                    <award>Best Picture</award>
                  </movie>
                </movies>
                '''
            ],[
                when: '/movies?y=1998',
                then: '''
                <movies year="1997">
                  <movie title="Silence of the Lambs">
                    <award>Best Picture</award>
                  </movie>
                </movies>
                '''
            ],[
                otherwise: '''
                <error>Unknown request ${request.url}</error>
                '''
            ]
        ]



        def evalJString = { str, obj, objName ->
            new Eval().me(objName, obj, "\"\"\"" + str + "\"\"\"");
        }

        def respondWithXml = { exchange, xmlStr ->
            exchange.getResponseHeaders().add("Content-Type", "text/xml")
            exchange.sendResponseHeaders(200, 0)
            Writer out = new OutputStreamWriter(exchange.getResponseBody());
            out.write(xmlStr)
            out.close()
            exchange.close();
        }

        def parser = new DefParser();
        parser.parse(contexts)

        def handlr = [
            handle: { HttpExchange ex ->
                def xmlStr = parser.find(ex.getRequestURI().toString())
                def gstr = evalJString(xmlStr, parser.lastRequest, 'request')
                respondWithXml(ex, gstr);

            } ] as HttpHandler


        server.createContext('/', handlr);

        server.start();
    }

    static void main(args) {
        new PoxerServ().run(Integer.parseInt(args[0]), args[1]);
    }
}

